package net.droiding.server.parser;

import java.util.ArrayList;
import java.util.List;

import net.droiding.server.pojo.Station;

import electric.xml.Document;
import electric.xml.Element;
import electric.xml.Elements;
import electric.xml.XPath;

public abstract class AbstractKmlParser implements KmlParser {
	
	
	public AbstractKmlParser() {
	}
	protected abstract Station createStation(String description, String coordinates);
	
	public List<Station> parse(byte[] kml) {
		
		Document doc = null;
		try {
			doc = new Document(kml);
			Elements placemarks = doc.getElements(new XPath("/kml/Document/Placemark"));
			List<Station> stations = new ArrayList<Station>();
			while (placemarks.hasMoreElements()) {
				try {
					Element placemark = placemarks.next();
					String description = placemark.getElement("description").getTextString();
					String coordinates = placemark.getElement("Point").getElement("coordinates").getTextString();
					Station station = createStation(description, coordinates);
					if (station != null) 
						stations.add(station);
				} catch (Throwable t) {
					//TODO log
					continue;
				}
			}
			return stations;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
}
